package com.microserivce.controller;

import com.microserivce.bean.TestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.security.Principal;

@RestController
public class DemoController {

    @LoadBalanced
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private TestBean bean;

    @PreAuthorize("hasRole('USER')")
    @RequestMapping(path = "/name")
    public String name(Principal principal) {
        String name = restTemplate.getForObject("http://demo-b/name", String.class);
        return principal.getName() + "（A） & " + name;
    }

    @PreAuthorize("hasRole('USER')")
    @RequestMapping(path = "/bean")
    public String bean() {
        return String.format("{\"key1\":\"%s\",\"key2\":\"%s\"}", bean.getKey1(), bean.getKey2());
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}
